package com.using.http.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import jxl.common.Logger;

public class HttpRequestTool {
	private static Logger logger = Logger.getLogger(HttpRequestTool.class);
	public static void main(String[] args) {
		logger.info(uploadFile(
				"http://t2.imgchili.com/33610/33610091_g_b014.jpg", "c:/"));
	}

	public static String uploadFile(String strUrl, String folder) {

		String fileName = strUrl.substring(strUrl.lastIndexOf("/") + 1);
		String path = folder + fileName;
		HttpURLConnection connection = null;
		try {
			URL url = new URL(strUrl);
			// 打开url连接
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 发送
			InputStream in = url.openStream();
			byte[] bytes = new byte[1024];
			int a = 0;
			OutputStream out = new FileOutputStream(new File(path));
			while ((a = in.read(bytes)) > 0) {
				out.write(bytes, 0, a);
			}
			out.flush();
			in.close();
			out.close();
			connection.disconnect();
			return fileName.trim();
		} catch (Exception e) {
			if (connection != null) {
				connection.disconnect();
			}
			logger.info(strUrl + "，" + e.getMessage());
			return null;
		}
	}

	/**
	 * 请求页面
	 * 
	 * @param strUrl
	 * @param strPostRequest
	 * @param maxLength
	 * @param code
	 * @return
	 */
	public static String getPageContent(String strUrl, String strPostRequest,
			int maxLength, String code) {
		// 读取结果网页
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection connection = null;
		try {
			URL url = new URL(strUrl);
			// 打开url连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置url请求方式 ‘get’ 或者 ‘post’
			connection.setRequestMethod(strPostRequest);
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 发送
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream(), code));
			int ch;
			for (int length = 0; (ch = in.read()) > -1
					&& (maxLength <= 0 || length < maxLength); length++) {
				buffer.append((char) ch);
				// System.out.print((char) ch);
			}
			in.close();
			connection.disconnect();
			return buffer.toString().trim();
		} catch (Exception e) {
			if (connection != null) {
				connection.disconnect();
			}
			logger.info(strUrl + "，" + e.getMessage());
			return null;
		}
	}
}
